package io.renren.modules.userdata.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sun.media.jfxmedia.logging.Logger;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.SysConfigDao;
import io.renren.modules.sys.entity.SysConfigEntity;
import io.renren.modules.userdata.entity.TLabelEntity;
import io.renren.modules.userdata.entity.TUserDataEntity;
import io.renren.modules.userdata.service.TUserDataService;
import io.renren.modules.userdata.service.UserDataManagerService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 用户画像管理服务
 * @author owen
 * @date 2018/11/2 9:39
 */
@Slf4j
@Service("userDataManagerService")
public class UserDataManagerServiceImpl implements UserDataManagerService {

    @Autowired
    private MultDataService multDataService;

    @Autowired
    private TUserDataService tUserDataService;

    /**
     * 数据库表名
     */
    public static final String TABLE_NAME="hibernate_sequences sys_dictionary sys_dictionary_type sys_permission sys_resource sys_role sys_role_auth sys_support_staff sys_user sys_user_role t_advertise t_app_config t_app_config_type t_app_version t_attach_busi_infor t_attach_contract t_attach_photo t_attach_user_busi_infor t_authdata_51data t_authdata_auth t_authdata_linkface_liveness_idnumber_verification t_authdata_linkface_liveness_selfie_verification t_authdata_living t_authdata_moxie t_authdata_temp_auth t_authdata_tobacco t_bank_bin t_bank_support t_bank_thirdparty_support t_card t_card_limit_log t_card_status_log t_channel t_contract_fadd_config t_contract_fadd_detail t_contract_fadd_job t_data_area t_data_contact t_data_idcard t_data_person t_data_tongdun t_data_work t_fund t_fund_amount_detail t_joint_loan t_joint_loan_data t_joint_register_info t_loan_order t_loan_order_log t_loan_supply_log t_loan_supply_requirement t_mail_detail t_mq_log t_notice t_notice_detail t_notice_template t_product t_product_config t_product_main_package t_product_money_feature t_product_rateplan_feature t_product_term_feature t_product_term_fee_feature t_product_type t_rate_plan t_rate_plan_detail t_rate_plan_detail_snapshot t_rate_plan_snapshot t_rate_plan_term t_rate_plan_term_snapshot t_repay_order t_repay_plan t_repay_plan_component t_tencent_living_order t_unoin_register_login_user t_user t_user_bank_card t_user_bank_card_bind t_user_fund_bank_card t_user_token t_user_weixin test_account test_fans";

    static String name="";

    @Data
    public class Result{
        private int index;
    }

    @Override
    public Map<String,String> clearData(Long userId) {
        String[] tableNameArr=TABLE_NAME.split(" ");
        Integer flag=0;
        Integer flag2=0;
        String res="";
        for(String arr:tableNameArr){
            String sql="delete from "+arr+" where user_id='"+userId+"';";
            boolean ll=false;
            int result=0;
            try {
                multDataService.execSql(sql+"\t");
                ll=true;
            }catch(Exception e){
                continue;
            }finally{
                if(ll){
                    System.out.println(sql);
                    res+=arr+",";
                    flag+=result;
                }
            }
            flag2+=1;
        }
        multDataService.execSql("delete from t_user where id="+userId);
        Map<String,String> map=new HashMap<String,String>();
        map.put("ok_res","执行结果："+"成功【"+flag.toString()+"】");
        map.put("fail_res","失败【"+flag2+"】");
        map.put("ok_table","成功的表名【"+res+"】");
        return map;
    }

    @Override
    public void saveData(TLabelEntity tLabel) {
        // 用户编号
        Long userId=tLabel.getUserId();
        // 标签编号
        Long labelId=tLabel.getId();
        String arr[]=TABLE_NAME.split(" ");
        String noUserIdTable="";
        for(int i=0;i<arr.length;i++){
            // 表名
            String tableName=arr[i];
            try {
                String searchSql="";
                if(arr[i].equals("t_user")){
                    searchSql="select * from " + arr[i] + " where id='" + userId + "'";
                }else{
                    searchSql="select * from " + arr[i] + " where user_id='" + userId + "'";
                }
                List<Map<String, Object>> list = multDataService.execSql(searchSql);

                if(list.size()>0){
                    System.out.println("执行查询sql:"+searchSql);
                    System.out.println("查询结果："+list.size());
                }

                List<String> listSql=new ArrayList<>();
                for (int j = 0; j < list.size(); j++) {
                    Map<String, Object> mapTable = list.get(j);
                    String key="";
                    String val="";
                    for (Map.Entry<String, Object> entry : mapTable.entrySet()) {
                        key+= entry.getKey()+",";
                        if(null==entry.getValue()){
                            val+="null,";
                        }else if(entry.getValue().equals("null")){
                            val+= entry.getValue()+",";
                        }else{
                            if(null==entry.getValue()){
                                val+="null,";
                            }else if(entry.getValue() instanceof Long){
                                val+= entry.getValue()+",";
                            }else if(entry.getValue() instanceof Integer){
                                val+= entry.getValue()+",";
                            }else if(entry.getValue() instanceof Boolean){
                                val+= entry.getValue()+",";
                            }else{
                                val+= "'"+entry.getValue()+"',";
                            }
                        }
                    }
                    key=key.substring(0,key.length()-1);
                    val=val.substring(0,val.length()-1);

                    String sql="INSERT INTO "+arr[i]+" ("+key+") VALUES ("+val+")";
                    listSql.add(sql);
                }

                if(!CollectionUtils.isEmpty(listSql)){
                    // 入库
                    TUserDataEntity tUserDataEntity=new TUserDataEntity();
                    tUserDataEntity.setLabelId(labelId);
                    tUserDataEntity.setCreateTime(new Date());
                    tUserDataEntity.setUserId(userId);
                    tUserDataEntity.setTableName(tableName);
                    tUserDataEntity.setUserData(joinArr(listSql));
                    tUserDataEntity.setCount(listSql.size());
                    tUserDataService.insert(tUserDataEntity);
                }
            }catch (Exception e){
                log.info("导出数据异常："+e.getMessage());
                noUserIdTable+=arr[i]+",";
            }
        }
    }


    public String joinArr(List<String> list){
        if(!CollectionUtils.isEmpty(list)&&list.size()>1){
            String str="";
            for(int i=0;i<list.size();i++){
                if(list.get(i)!=null){
                    str+=(list.get(i)+";#split#");
                }
            }
            str=str.substring(0,str.length()-9);
            return str;
        }
        return list.get(0);
    }

    @Override
    public void rollBackData(Long userId, Long labelId) {

        clearData(userId);

        int tableFlag=0; //成功的表
        int sumIndex=0; //成功的总条数
        try {

            Map<String, Object> params=new HashMap<String,Object>();
            params.put("user_id",userId);
            params.put("label_id",labelId);
            params.put("limit","10000");
            params.put("page","1");
            PageUtils page = tUserDataService.queryPage(params);
            List<TUserDataEntity> list= (List<TUserDataEntity>) page.getList();
            System.out.println("回滚的总条数："+list.size());



            for(TUserDataEntity tUserDataEntity:list){
                String text=tUserDataEntity.getUserData();
                String tableName=tUserDataEntity.getTableName();
                // TODO: 2018/11/13
                String[] userDataArr=text.split("#split#");
                int flag=0;
                for(String strData:userDataArr){
                    multDataService.execSql(strData);
                    flag+=1;
                    sumIndex+=1;
                }
                if(flag==userDataArr.length){
                    tableFlag+=1;
                }

            }



            /* for (File file : list) {
                FileReader fileReader = new FileReader(path + "\\" + file.getName());
                String sql = fileReader.readString().trim();
                String[] arr = sql.split("\n");
                Result result = new Result();
                Arrays.stream(arr).forEach(str -> execSql(str, result));
                System.out.println(result.getIndex());
                sumIndex += result.getIndex();
                index += 1;
            }*/
            if(tableFlag!=list.size()){
                throw new RRException("回滚失败");
            }
        }catch (Exception e){
            System.err.println(name);
            e.printStackTrace();
        }
        System.out.println("成功的表数量："+ tableFlag);
        System.out.println("成功的总条数："+sumIndex);
    }
}
